package com.example.first.activities;



import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.Toolbar;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.example.first.R;
import com.example.first.adapters.CartAdapter;
import com.example.first.adapters.CategoryAdapter;
import com.example.first.adapters.DishAdapter;
import com.example.first.modle.ApiResponse;
import com.example.first.modle.CartItem;
import com.example.first.modle.Category;
import com.example.first.modle.Dish;
import com.example.first.services.ApiService;
import com.example.first.utils.RetrofitClient;
import com.google.android.material.snackbar.Snackbar;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MainActivity extends AppCompatActivity{

    private ListView listViewCategories;
    private CategoryAdapter categoryAdapter;
    private DishAdapter dishAdapter;
    private List<Category> categories;
    private List<Dish> dishes;
    private ListView listViewDishes;

    private int currentCategoryPosition=0;

    //测试登录按钮
    private Button button;

    //购物车相关
    private List<CartItem> cartItems;
    private CartAdapter cartAdapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);




        // 设置 Toolbar 标题
        if (getSupportActionBar() != null) {
            getSupportActionBar().setTitle("外卖订餐");
        }


        // 设置状态栏颜色
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.parseColor("#FFC300")); // 设置为你想要的颜色
        }

        //初始化RetrofitClient
        RetrofitClient.init(this);

        listViewCategories =findViewById(R.id.list_view_categories);
        listViewDishes=findViewById(R.id.list_view_dishes);

        button=findViewById(R.id.contact_button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //处理点击事件,启动personActivity
                Intent intent=new Intent(MainActivity.this,PersonActivity.class);
                startActivity(intent);

            }
        });


        //初始化
        categories=new ArrayList<>();
        dishes=new ArrayList<>();
        categoryAdapter= new CategoryAdapter(this,categories);
        dishAdapter=new DishAdapter(this,dishes,cartItems,this);

        listViewCategories.setAdapter(categoryAdapter);
        listViewDishes.setAdapter(dishAdapter);



        cartItems=new ArrayList<>();


        // 设置悬浮容器的点击事件
        View floatingContainer = findViewById(R.id.floating_container);
        floatingContainer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDialog(v);
            }
        });

        // 设置图像的点击事件
        View imageView = findViewById(R.id.image_view);
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDialog(v);
            }
        });
        // 设置文本的点击事件
        TextView textView = findViewById(R.id.text_view);
        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDialog(v);
            }
        });
        // 设置按钮的点击事件
        Button button1 = findViewById(R.id.button);
        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDialog(v);
            }
        });

        //已登录情况才读取购物车信息,否则填充其他信息
        if(RetrofitClient.getToken()!=null)
        {
            //获取购物车数据
            textView.setTextSize(24);
            getCartList();
        }else {
            textView.setText("未登录,登陆后查看");
            textView.setTextSize(20);
        }


        //获取分类数据
        getCategoryList();

        //设置点击监听器
        listViewCategories.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                //处理点击事件,更新右侧商品列表
                getDishList(categories.get(position).getId());
                currentCategoryPosition=position;
            }
        });






        //测试:::显示登录状态
        //TextView textView1=findViewById(R.id.business_description_text);
        //textView1.setText("token:"+RetrofitClient.getToken());



    }


    //提交订单
    public void orderSubmit()
    {
        if(cartItems.size()==0)
        {
            Snackbar.make(listViewDishes, "购物车为空", Snackbar.LENGTH_SHORT).show();
            return;
        }
        Intent intent=new Intent(MainActivity.this,OrderSubmitActivity.class);

        startActivity(intent);

    }





    //获取购物车数据
    public void getCartList(){
        ApiService apiService = RetrofitClient.getApiService();
        Call<ApiResponse<List<CartItem>>> call = apiService.getCartList();
        call.enqueue(new Callback<ApiResponse<List<CartItem>>>() {
            @Override
            public void onResponse(Call<ApiResponse<List<CartItem>>> call, Response<ApiResponse<List<CartItem>>> response) {

                if (response.isSuccessful() && response.body() != null) {
                    ApiResponse<List<CartItem>> apiResponse = response.body();
                    cartItems = apiResponse.getData();

                    updateFloat();
                } else if (response.code() == 401) {
                    Toast.makeText(MainActivity.this, "未登录,请先登录", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<ApiResponse<List<CartItem>>> call, Throwable t) {
                Log.d("MainActivity", "onFailure thread: " + Thread.currentThread().getName());
                Log.e("MainActivity", "onFailure: " + t.getMessage(), t);
                Toast.makeText(MainActivity.this, "获取购物车数据失败", Toast.LENGTH_SHORT).show();
            }
        });
    }


    //更新浮窗内容
    private void updateFloat() {
        if (!cartItems.isEmpty()) {
            BigDecimal amounts = BigDecimal.ZERO;
            for (CartItem cartItem : cartItems) {
                BigDecimal amount = cartItem.getAmount();
                BigDecimal number = new BigDecimal(cartItem.getNumber());
                amounts = amounts.add(amount.multiply(number));
            }
            TextView priceTextView = findViewById(R.id.text_view);
            priceTextView.setText("￥" + amounts.toString());
        }else {
            TextView priceTextView = findViewById(R.id.text_view);
            priceTextView.setText("￥" + "0");
        }
    }

    //显示购物车详情
    private void showDialog(View anchorView) {

        if(RetrofitClient.getToken()==null){
            Toast.makeText(this, "未登录,请先登录", Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(this, LoginActivity.class);
            this.startActivity(intent);
            this.finish();
            return;
        }
        // 创建一个 Dialog
        Dialog dialog = new Dialog(this, R.style.DialogTheme);
        dialog.setContentView(R.layout.cart_details_dialog);

        // 获取布局中的视图
        ListView cartListView = dialog.findViewById(R.id.cart_list_view);

        Button button1 = dialog.findViewById(R.id.button);
        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 处理按钮点击事件
                orderSubmit();
            }
        });

        //存在线程问题,异步调用,获取之前后续操作需在回调函数中执行
        //getCartList();

        ApiService apiService = RetrofitClient.getApiService();
        Call<ApiResponse<List<CartItem>>> call = apiService.getCartList();
        call.enqueue(new Callback<ApiResponse<List<CartItem>>>() {
            @Override
            public void onResponse(Call<ApiResponse<List<CartItem>>> call, Response<ApiResponse<List<CartItem>>> response) {
                if (response.isSuccessful() && response.body()!=null){
                    if (response.body().getCode()==1){
                        //成功
                        cartItems=response.body().getData();
                        // 初始化 CartAdapter 并设置给 ListView
                        cartAdapter = new CartAdapter(MainActivity.this, cartItems,dialog,MainActivity.this);
                        cartListView.setAdapter(cartAdapter);

                        // 计算总金额并显示
                        if (!cartItems.isEmpty()) {
                            BigDecimal amounts = BigDecimal.ZERO;
                            for (CartItem cartItem : cartItems) {
                                BigDecimal amount = cartItem.getAmount();
                                BigDecimal number = new BigDecimal(cartItem.getNumber());
                                amounts = amounts.add(amount.multiply(number));
                            }
                            TextView viewById = dialog.findViewById(R.id.text_view);
                            viewById.setText("￥" + amounts.toString());
                        }

                        // 设置 Dialog 的宽度和高度
                        WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
                        layoutParams.copyFrom(dialog.getWindow().getAttributes());
                        layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
                        layoutParams.height = getResources().getDisplayMetrics().heightPixels * 2 / 3;
                        layoutParams.gravity = Gravity.BOTTOM;
                        dialog.getWindow().setAttributes(layoutParams);


                        //关闭dialog时调用getCartList()
                        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                            @Override
                            public void onDismiss(DialogInterface dialog) {
                                getCartList();
                                updateFloat();
                                getDishList(categories.get(currentCategoryPosition).getId());
                            }
                        });

                        // 显示 Dialog
                        dialog.show();

                    }else {
                        Toast.makeText(MainActivity.this, response.body().getMsg(), Toast.LENGTH_SHORT).show();
                    }
                }else {
                    Toast.makeText(MainActivity.this, "获取购物车数据失败", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<ApiResponse<List<CartItem>>> call, Throwable t) {
                Toast.makeText(MainActivity.this, "请求失败", Toast.LENGTH_SHORT).show();
            }
        });








    }


    /**
     * 获取分类数据
     */
    private void getCategoryList() {
        //获取数据
        ApiService apiService = RetrofitClient.getApiService();
        Call<ApiResponse<List<Category>>> call = apiService.getCategoryList(1);
        call.enqueue(new Callback<ApiResponse<List<Category>>>() {
            @Override
            public void onResponse(Call<ApiResponse<List<Category>>> call, Response<ApiResponse<List<Category>>> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if(response.body().getCode()==1){
                        // 成功获取数据
                        ApiResponse<List<Category>> apiResponse =response.body();
                        categories =apiResponse.getData();
                        // 更新适配器
                        categoryAdapter.setCategories(categories);
                        // 通知适配器数据已更改
                        categoryAdapter.notifyDataSetChanged();
                        // 确保 categories 不为空后再调用 getDishList
                        if (!categories.isEmpty()) {
                            getDishList(categories.get(0).getId());
                            currentCategoryPosition = 0;
                        }
                    }else {
                        Toast.makeText(MainActivity.this, response.body().getMsg(), Toast.LENGTH_SHORT).show();
                    }

                }
            }

            @Override
            public void onFailure(Call<ApiResponse<List<Category>>> call, Throwable t) {
                // 处理失败情况
                ImageView errorImage=findViewById(R.id.error_image);
                ListView category=findViewById(R.id.list_view_categories);
                ListView dish=findViewById(R.id.list_view_dishes);
                errorImage.setVisibility(View.VISIBLE);
                category.setVisibility(View.GONE);
                dish.setVisibility(View.GONE);

                //设置图片点击事件
                errorImage.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        errorImage.setVisibility(View.GONE);
                        category.setVisibility(View.VISIBLE);
                        dish.setVisibility(View.VISIBLE);
                        //重新加载数据
                        getCategoryList();
                        getCartList();
                    }
                });
            }
        });
    }

    /**
     * 获取菜品数据列表
     * @param categoryId
     */
    private void getDishList(int categoryId) {
        ApiService apiService = RetrofitClient.getApiService();
        Call<ApiResponse<List<Dish>>> call = apiService.getDishList(categoryId);
        call.enqueue(new Callback<ApiResponse<List<Dish>>>() {
            @Override
            public void onResponse(Call<ApiResponse<List<Dish>>> call, Response<ApiResponse<List<Dish>>> response) {
                if(response.isSuccessful() && response.body() != null){
                    //成功发送请求
                    ApiResponse<List<Dish>> apiResponse = response.body();
                    dishes = apiResponse.getData();
                    //更新适配器
                    dishAdapter.setDishes(dishes,cartItems);
                    //通知适配器数据已更改
                    dishAdapter.notifyDataSetChanged();

                }
            }

            @Override
            public void onFailure(Call<ApiResponse<List<Dish>>> call, Throwable t) {
                //处理失败情况
                t.printStackTrace();
            }
        });


    }

    /**
     * 退出前确认
     */
    @SuppressLint("MissingSuperCall")
    @Override
    public void onBackPressed() {

        // 创建一个确认对话框
        new AlertDialog.Builder(this)
                .setTitle("确认退出")
                .setMessage("您确定要退出应用吗？")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 用户点击确定，结束当前Activity
                        finish(); // 结束当前Activity
                    }
                })
                .setNegativeButton("取消", null)
                .show();
    }



}